/*
 * @Description:
 * @Autor: lcz
 * @LastEditors: lcz
 * @LastEditTime: 2023-10-16 13:17:30
 */
import { normalizePath } from "vite";

interface BuryingPointProps {
  include: string | string[];
}

export default function BuryingPoint(options?: BuryingPointProps): any {
  const { include } = options || {};
  // console.log(include,'include include')
  if (!include) {
    console.error("vite-plugin-buryingPoint: include params must exist");
  }
  let includePath = Array.isArray(include) ? include : !!include ? [include] : [];
  //  规范路径2种方式都行
  // if (process.platform === "win32") includePath = includePath.map(item => item.replace(/\\/g, "/"));
  includePath = includePath.map(item => normalizePath(item));
  return {
    type: "vite-plugin-buryingPoint",
    // code 解析后的源代码 id 文件路径
    transform(code: string, id: string) {
      // console.log(code, "code");
      if (includePath.includes(id) && (id.endsWith(".tsx") || id.endsWith(".jsx"))) {
        console.log(id, "id");

        const addWatch = `
        (()=>{
          const url = "https://api.angineglobal.com/angine/common/bannerItemInfo/page";
      
          const requestConfig = {
            credentials: 'include', //（ 允许 cookie 共享，跨域问题，传Cookie是必须配置）
            method: "post",
            mode: "cors", // 跨域
            headers: {
              Accept: 'application/json', // 用户代理可处理的媒体类型// 用户代理可处理的媒体类型
              'Content-Type': 'application/json' // 报文主体对象类型
            },
            cache: 'force-cache' //缓存 default
          };
      
          Object.defineProperty(requestConfig, "body", {
            value: JSON.stringify({
              positionCode: "PC_Home"
            })
          });
          
          fetch(url, requestConfig).then(res=> res.json()).then((res)=>{
            console.log(res)
          })
        })();
      `;
        return {
          // 将自定义 Hooks 代码插入到原始代码前面
          code: code + addWatch,
          map: null // 暂不生成 source map
        };
      }
    }
  };
}
